<template>
  <el-row>
    <el-col >
      <el-button type="success" @click="GetAddRole()">新增角色</el-button>
    </el-col>
  </el-row>
  
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="roleId" label="编号" width="120" />
      <el-table-column prop="roleName" label="角色名称" width="120">
      <template v-slot="scope">
        <el-button link size="small" @click="showRoleUser( scope.row.roleId,scope.row.roleName)">{{ scope.row.roleName }}</el-button>
      </template>
      </el-table-column>
      <el-table-column prop="createPeople" label="创建人"width="120" />
      <el-table-column prop="createtime" label="创建时间" width="180">
        <template v-slot="scope">
            {{scope.row.createtime.substring(0,10)+" "+scope.row.createtime.substring(11,19)}}
        </template>
      </el-table-column>
      <el-table-column prop="updatePeople" label="更新人"width="120" />
      <el-table-column prop="updatetime" label="更新时间"  width="180">
        <template v-slot="scope">
            <div v-if="scope.row.updatetime!=null">
                {{  moment(scope.row.updatetime).format("YYYY-MM-DD HH:mm:ss")}}
            </div>
           
        </template>
      </el-table-column>
      <el-table-column prop="" label="操作" >
        <template v-slot="scope">
            <el-button link type="danger" size="small" @click="DeleteRole(scope.row.roleId)">删除</el-button>
        <el-button link type="primary" size="small"  @click="FanTian(scope.row.roleId)">修改</el-button>
        <el-button link type="success" size="small" @click="FenpeiRole(scope.row)">分配人员</el-button>
        </template>
        
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="page.pageindex"
      v-model:page-size="page.pagesize"
      :page-sizes="[15, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.totalcount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    />
  </div>

    <!-- 修改弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="更新角色" width="500">
    <el-form :model="form">
      <el-form-item label="角色名称" :label-width="formLabelWidth">
        <el-input v-model="form.roleName" autocomplete="off" />
      </el-form-item>
      
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button type="primary" @click="UpdateRole()">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

<!-- 分配员工弹窗 -->
<el-dialog v-model="dialogFormVisible1" width="600"height="500" draggable  >
  <p>请设置【{{RoleNameNice.roleName}}】角色的员工</p>
  <div class="common-layout">
    <el-container>
      <el-container>
        <el-aside width="150px">
   <!-- 部门多选框 -->
  <div>
    <div v-for="option in options" :key="option.value">
      <input type="checkbox" :value="option.value" v-model="selectedOptions" @change="getdepentment">
      <label>{{ option.text }}</label>
    </div>
  </div>
        </el-aside>
        <el-main>

        <!-- 员工树 -->
        <div>
          <p>选择员工</p>
    <div v-for="items in data">
      <input type="checkbox" :value="items.userId" v-model="RoleNameNice.userIds"  >
      
      <label>{{ items.userName }}</label>
    </div>
  </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
  <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">关闭</el-button>
        <el-button type="primary" @click="AddAppUserRole()">
          确认保存
        </el-button>
      </div>
    </template>
  </el-dialog>
 <!-- 点击角色名称跳转弹框 -->
 <el-dialog v-model="dialogFormactanle" width="500">

  <p>属于角色【{{roleNamesreq.roleName}}】的员工如下</p>
  <el-button type="success" @click="AppAddUserRole(roleNamesreq.roleName)">新增用户</el-button>
  <el-table :data="roleUserName" border style="width: 100%">
    <el-table-column  label="用户">
      <template v-slot="scope">
        {{scope.row.userName}}
      </template>
    </el-table-column>

   
    <el-table-column  label="操作">
      <template v-slot="scope">
        <el-button type="danger" style="width: 60px;height: 20px;" @click="Deleteuserrole(RoleNameNice.roleId,scope.row.userId)">x</el-button>
      </template>
    </el-table-column>
    
  

  </el-table>
  </el-dialog>
  </template>
  
  <script lang="ts" setup>
     import { regionData } from 'element-china-area-data'
   import { onMounted, reactive, ref,computed } from 'vue'
  import { ElMessage,ElMessageBox, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
  import axios from 'axios'
  import {useRouter,useRoute} from 'vue-router'
import {useCounterStore} from '@/stores/counter'
import Store from 'element-plus/es/components/cascader-panel/src/store.mjs'
import moment, { isDate } from 'moment'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { column } from 'element-plus/es/components/table-v2/src/common.mjs'
let route=useRoute();
let stroe=useCounterStore();
let router=useRouter();

//挂载函数显示角色列表
onMounted(()=>{
    getlist();

})
//角色分页所需数据
const page=reactive({
    pageindex:1,
    pagesize:15,
    totalcount:0,
    totalpage:0,
})
//角色列表
const getlist=()=>{
    axios({
        url:'http://localhost:5284/api/Role/QueryRole',
        method:'get',
        params:{
            Pageindex:page.pageindex,
            Pagesize:page.pagesize
        }
        
        })
        .then(res=>{
            if(res.data.code==101){
                tableData.value=res.data.list;
                page.totalcount=res.data.totalCount;
                page.totalpage=res.data.totalPage;
            }
    })
}

//存储角色数据的变量
const tableData = ref([]);

//删除角色
const DeleteRole = (roleId:any) => {
  ElMessageBox.confirm(
    '您确定要操作吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
        axios({
        url:'http://localhost:5272/api/Role/DeleteRole',
        method:'put',
        data:{
            roleId:roleId
        }
    })
    .then(res=>{
        if(res.data.code=101){
            ElMessage({
        type: 'success',
        message: '操作成功',
      })
      getlist();
        }
    })
      
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}

//修改角色
const dialogFormVisible = ref(false)
const dialogFormVisible1 = ref(false)
const dialogFormactanle = ref(false)
const formLabelWidth = '140px'
//修改角色所需数据
const form = reactive({
    roleId:"",
    roleName: '',
    updatePeople:'',
})
//反填角色
const FanTian=(roleId:any)=>{
    axios({
        url:'http://localhost:5284/api/Role/GetRoleId',
        method:'get',
        params:{
            RoleId:roleId
        }
    })
    .then(res=>{
        if(res.data.code==101){
            form.roleId=res.data.data[0].roleId;
            form.roleName=res.data.data[0].roleName;
            
        }
    })
    dialogFormVisible.value=true;
}
//更新角色
const UpdateRole=()=>{
    axios({
        url:'http://localhost:5272/api/Role/UpdateRole',
        method:'put',
        data:{
            roleId:form.roleId,
            roleName:form.roleName,
            updatePeople:stroe.CurrLoginUser.UserName
        }
    })
    .then(res=>{
        if(res.data.code==101){
            ElMessage.success("更新成功")
            dialogFormVisible.value=false;
            getlist();
        }
        else{
            ElMessage.error(res.data.message)
        }
    })
}
//分页页容量变化监听方法
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  page.pagesize=val;
  getlist();
}
//分页当前页变化监听方法
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  page.pageindex=val;
  getlist();
}





//部门静态数据
const options=ref([
{ value: '1', text: 'IT信息部' },
  { value: '2', text: '人力资源部' },
  { value: '3', text: '销售部' },
  { value: '4', text: '财务部' },
  { value: '5', text: '行政部' }
])
//存储选中的部门
const selectedOptions = ref([]);
//根据部门id查询用户
const getdepentment=(value:any)=>{
  axios({
    url:'http://localhost:5284/api/Role/GetDepentId',
    method:'get',
    params:{
      DepenmentIds:selectedOptions.value.join(",")
    } 
  })
  .then(res=>{
    if(res.data.code==101){
      data.value=res.data.data
    }
  })
}
//存储查询出来的用户数据
const data =ref([]);



//添加用户角色数据
const RoleNameNice=reactive({
  roleId:'',
  roleName:'',
  userIds:[]
})
//分配角色用户
const FenpeiRole=(row:any)=>{
  RoleNameNice.roleId=row.roleId
  RoleNameNice.roleName=row.roleName
  //反填部门用户角色关系
  FanTianUserRole()
dialogFormVisible1.value=true;
}
//根据角色id查询部门
const FanTianUserRole=()=>{
axios({
  url:'http://localhost:5284/api/Role/QueryUserDepent',
  method:'get',
  params:{
    RoleId:RoleNameNice.roleId
  }
})
.then(res=>{
  if(res.data.code==101){
    console.log(res)
    selectedOptions.value = res.data.list.map((dep:any)=>dep.depenmentId);
      console.log(selectedOptions.value, "depentmentId");
      getdepentment(selectedOptions);
      RoleNameNice.userIds=res.data.list.map((ect:any)=>ect.userId)
  }
})
}
const depentmentids=ref([]);
const roleUserName=ref([])


//添加用户角色关系
const AddUserRole=()=>{
  console.log(data)
  console.log(RoleNameNice.userIds)
  console.log(RoleNameNice.roleId)
  axios({
    url:'http://localhost:5272/api/UserRole/AddUserRole',
    method:'post',
    data:{
      userIds:RoleNameNice.userIds,
      roleId:RoleNameNice.roleId,
    }
  })
  .then(res=>{
    if(res.data.code==101){
      ElMessage.success("新增成功")
      dialogFormVisible1.value=false;
      router.push("/ShowUser")
    }
  })
}

const roleNamesreq=reactive({
  roleName:'',
})

const selectedRow = reactive({
    ckroleId: 0,
    ckroleName: "",

});
//角色名下有哪些用户
const showRoleUser=(roleIds:any,roleName:any)=>{
  RoleNameNice.roleId=roleIds,
  roleNamesreq.roleName=roleName,
  console.log(RoleNameNice)
  dialogFormactanle.value=true;
  selectedRow.ckroleId=roleIds,
  selectedRow.ckroleName=roleName;
  getroleUser()
  FanTianUserRole();
  
}
//查询角色名下有哪些用户的方法
const getroleUser=()=>{
  axios({
    url:'http://localhost:5284/api/Role/GetRoleQueryUser',
    method:'get',
    params:{
      RoleId: RoleNameNice.roleId
    }
  })
  .then(res=>{
    if(res.data.code==101){
      roleUserName.value=res.data.list
      
    }
  })
}



//删除角色名下的用户
 const Deleteuserrole=(roleId:any,userId:any)=>{
  ElMessageBox.confirm(
    '您确定要操作吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
        axios({
          url:'http://localhost:5272/api/UserRole/DeleteRoleUser',
          method:'put',
          data:{
            userId:userId,
            roleId:roleId
          }
    })
    .then(res=>{
        if(res.data.code=101){
            ElMessage({
        type: 'success',
        message: '操作成功',
      })
      getroleUser();
        }
    })
      
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
  // axios({
  //  
  // })
  // .then(res=>{
  //   if(res.data.code==101){
  //     ElMessage.success(res.data.message)
  //    
  //   }
  // })
 }

 //点击角色名称进入弹窗点击弹窗中的新增用户进入此方法
 const AppAddUserRole=(roleName:any)=>{
  RoleNameNice.roleName=roleName
  dialogFormVisible1.value=true;
 }

//点击角色名称进入弹窗点击弹窗中的新增用户的方法
const AddAppUserRole=()=>{
  axios({
    url:'http://localhost:5272/api/UserRole/PiDeleter',
    method:'delete',
    data:{
      roleId:RoleNameNice.roleId
    }
  })
  .then(res=>{
    if(res.data.code==101){
     
    }
  })
  AddUserRole()
}

//跳转到添加页面
const GetAddRole=()=>{
  router.push('/AddRole')
}



  </script>
  